/*
 *   Copyright 2021 zzh
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *
 */

package com.aduib.boot.common.util;

import com.aduib.boot.common.exception.CommonException;
import com.aduib.boot.common.exception.IoException;

/**
 * @description: ExceptionUtils
 * @author: zzh
 * @date: 2021/10/28 10:20
 */
public class ExceptionUtils {

  /**
   * 获得完整消息，包括异常名，消息格式为：{SimpleClassName}: {ThrowableMessage}
   *
   * @param e 异常
   * @return 完整消息
   */
  public static String getMessage(Throwable e) {
    if (null == e) {
      return StrUtils.NULL;
    }
    return StrUtils.format("{}: {}", e.getClass().getSimpleName(), e.getMessage());
  }

  /**
   * 获得消息，调用异常类的getMessage方法
   *
   * @param e 异常
   * @return 消息
   */
  public static String getSimpleMessage(Throwable e) {
    return (null == e) ? StrUtils.NULL : e.getMessage();
  }

  /**
   * 使用运行时异常包装编译异常<br>
   *
   * <p>如果传入参数已经是运行时异常，则直接返回，不再额外包装
   *
   * @param throwable 异常
   * @return 运行时异常
   */
  public static RuntimeException wrapRuntime(Throwable throwable) {
    if (throwable instanceof RuntimeException) {
      return (RuntimeException) throwable;
    }
    return new CommonException(throwable);
  }

  /**
   * 将指定的消息包装为运行时异常
   *
   * @param message 异常消息
   * @return 运行时异常
   */
  public static RuntimeException wrapRuntime(String message) {
    return new RuntimeException(message);
  }

  /**
   * 包装一个异常
   *
   * @param <T> 被包装的异常类型
   * @param throwable 异常
   * @param wrapThrowable 包装后的异常类
   * @return 包装后的异常
   */
  @SuppressWarnings("unchecked")
  public static <T extends Throwable> T wrap(Throwable throwable, Class<T> wrapThrowable) {
    if (wrapThrowable.isInstance(throwable)) {
      return (T) throwable;
    }
    return ClassUtils.newInstance(wrapThrowable, throwable);
  }

  public static void throwStreamAlreadyClosedException(boolean isClosed){
    if (isClosed) {
      throw new IoException("stream is closed");
    }
  }


}
